/**
 * @Description: vuepress小型的状态管理
 * @Author BPF
 * @create 2021/11/9 11:08
 */
import Vue from 'vue'
import { make, useVuexPersistenceDecorator, VUE_PRESS_LOCALSTORAGE, isBrowser } from './helper'

const store = isBrowser ? JSON.parse(localStorage.getItem(VUE_PRESS_LOCALSTORAGE)) || null : null

const state = Vue.observable({
  size: store?.size || 'default', // element 组件的尺寸， medium、small、mini
  theme: store?.theme || 'default' // 主题
})

const reducers = {
  ...make.reducers(state),

  /**
   * 更改主题
   * @param payload
   */
  changeTheme(payload = '') {
    state.theme = payload
    let cssURL = `${BASE}theme/theme_${payload}/index.css`
    const xhr = new XMLHttpRequest()
    xhr.open('GET', cssURL, false)
    xhr.send()
    let styleDOM = document.querySelector('style#theme-style-body')
    styleDOM && styleDOM.remove()
    document.body.insertAdjacentHTML('beforeend', `<style id="theme-style">${xhr.response}</style>`)
  },

  /**
   * 更改主题尺寸大小
   * @param payload
   */
  changeSize(payload = '') {
    Vue.prototype.$ELEMENT = {
      ...Vue.prototype.$ELEMENT,
      size: payload || Vue.prototype.$ELEMENT.size
    }
  }
}

export default {
  state,
  reducers: useVuexPersistenceDecorator(state, reducers)
}
